import React, { useRef } from "react";
import { Form, Input, Button, Toast, NavBar } from "antd-mobile"; //组件
import { useNavigate } from "umi"; // 路由
import Qs from "qs";
import { getRegApi } from "@/api";
import axios from "axios";

export default function index() {
  /* 路由 */
  const navigate = useNavigate();

  // 获取email
  const email = useRef<any>(null);

  // 返回首页
  const back = () => navigate("/login");

  /* 表单提交 触发 callBack */
  const onFinish = async (values: any) => {
    const res = await getRegApi(values);
    if (res.data.code == "200") {
      Toast.show({
        content: "注册成功",
        afterClose: () => navigate("/login"),
      });
    }
  };

  // 获取验证码
  const sentPost = async () => {
    const sendEmail = {
      type: "register",
      email: email.current.nativeElement.value,
    };
    const res = await axios({
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      method: "post",
      url: "http://43.139.124.13:8888/user/email",
      data: Qs.stringify(sendEmail),
    });
  };

  return (
    <div className="fromRegister">
      <NavBar onBack={back}>注册页</NavBar>
      <Form layout="horizontal" onFinish={onFinish}>
        <Form.Item
          name="name"
          label="账号"
          rules={[{ required: true, message: "账号不能为空" }]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input placeholder="请输入密码" />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ required: true, message: "邮箱不能为空" }]}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <Input ref={email} placeholder="请输入邮箱" />
            <Button
              onClick={sentPost}
              size="mini"
              style={{ height: "0.8rem", width: 200 }}
            >
              发送验证码
            </Button>
          </div>
        </Form.Item>
        <Form.Item
          name="code"
          label="验证码"
          rules={[{ required: true, message: "验证码不能为空" }]}
        >
          <Input placeholder="请输入验证码" />
        </Form.Item>
        <Form.Item className="button">
          <Button block type="submit" color="danger" size="large">
            注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
